﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BSC_OTC_Management.Forms
{
    public partial class Frm_VanTinKH : Form
    {
        #region khaibaobien
        Code.CL_Ultility _cl = new Code.CL_Ultility();
        DataTable _tblView = new DataTable("View");
        DataTable _tblKhachHang = new DataTable("Khachhang");
        DataTable _tblSotraichu = new DataTable("Sotraichu");
        DataTable _tblTaikhoan = new DataTable("Taikhoan");

        #endregion

        public Frm_VanTinKH()
        {
            InitializeComponent();
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            try
            {
                string sql = "";
                string cmt = "";
                string makh = "";
                if (txt_cmt.Text.Length == 0)
                    return;

                cmt = txt_cmt.Text;
                /*sql = "SELECT a.makh,a.hoten,a.diachi,a.dienthoai,a.fax,a.email,a.cmt,a.gpkd,b.cdcontent as LOAIKH,c.cdcontent as quoctich "+
                      "FROM BSC_TBL_KHACHHANG a, allcode b, allcode c "+
                      "where a.loaikh = b.cdval and a.quoctich = c.cdval "+
                      "and  b.cdname='LOAIKH' and c.cdname='QUOCTICH' "+
                      "and b.cdtype='BSC_TBL_KHACHHANG' and c.cdtype='BSC_TBL_KHACHHANG' "+
                      "and a.cmt ='" + cmt  + "'";*/
                //table search sql
                DataTable table = new DataTable("Condition_Search");
                table.Columns.Add("COLUMNNAME");
                table.Columns.Add("PHEPTINH");
                table.Columns.Add("VALUE");
                table.Columns.Add("DATATYPE");
                DataRow dr = table.NewRow();
                dr["COLUMNNAME"] = "cmt";
                dr["PHEPTINH"] = "=";
                dr["VALUE"] = cmt;
                dr["DATATYPE"] = "T";
                table.Rows.Add(dr);
                //truy van
                _tblKhachHang = this._cl._services.SearchView_ByParameters("BSC_TBL_KHACHHANG", table);
                if (_tblKhachHang.Rows.Count > 0)
                {
                    //show title
                    makh = _tblKhachHang.Rows[0]["makh"].ToString();
                    lb_khachhang.Text = "Tên KH: " + _tblKhachHang.Rows[0]["hoten"] + "\r\n" +
                                        "Địa chỉ: " + _tblKhachHang.Rows[0]["diachi"] + " -- Điện thoại: " + _tblKhachHang.Rows[0]["dienthoai"] + "\r\n" +
                                        "CMND/GPKD: " + cmt + "/" + _tblKhachHang.Rows[0]["gpkd"] + " -- Loại KH: " + _tblKhachHang.Rows[0]["loaikh"];

                    //get danh muc trai phieu
                    sql = "Select a.matp, c.tentp, c.menhgia, a.maso,d.cdcontent as dotgopvon,a.slphothong,a.slhanche,a.slcamco "+
                          "FROM BSC_TBL_SOTRAICHU a, bsc_tbl_khachhang b, bsc_tbl_tpph c, allcode d "+
                          "where a.makh = b.makh "+
                          "and b.makh = '"+ makh + "' "+
                          "and a.matp = c.matp "+
                          "and a.dotgopvon = d.cdval "+
                          "and d.cdname='DOTGOPVON' " +
                          "and d.cdtype='BSC_TBL_SOTRAICHU'";
                    _tblSotraichu = _cl._services.GetDatatable_BySQL(sql);
                    _tblView = _cl._services.GetViewBy_SearchCode("BSC_TBL_SOTRAICHU");

                    //tinh tien trai phieu
                    if (_tblSotraichu.Rows.Count > 0)
                    {
                        double v_tienTP = 0;
                        double v_sl = 0;
                        double v_menhgia = 0;
                        foreach (DataRow row in _tblSotraichu.Rows)
                        {

                            v_sl = Convert.ToDouble(row["slphothong"]) + Convert.ToDouble(row["slhanche"]) + Convert.ToDouble(row["slcamco"]);
                            v_menhgia = Convert.ToDouble(row["menhgia"]);
                            v_tienTP += (v_sl * v_menhgia);
                        }
                        //tien co tren trai phieu
                        lb_Traiphieu.Text = String.Format("{0:#,##0.### VND}", v_tienTP);
                    }

                    //show du lieu len datagridview
                    _tblSotraichu.Columns.Remove("menhgia");
                    ShowResult(_tblSotraichu, _tblView); 

                    //show tien mat trong TK 
                    sql = "Select * from bsc_tbl_taikhoan tk where tk.makh ='" +makh+ "'";
                    _tblTaikhoan = _cl._services.GetDatatable_BySQL(sql);
                    if (_tblTaikhoan.Rows.Count > 0)
                    {
                        double v_tienmat = Convert.ToDouble(_tblTaikhoan.Rows[0]["sodu"]) + Convert.ToDouble(_tblTaikhoan.Rows[0]["phongtoa"]);
                        lb_Tien.Text = String.Format("{0:#,##0.### VND}", v_tienmat);
                    }
                }
                else
                    MessageBox.Show("Số chứng minh thư không tồn tại!", Code.StaticVariable.messeseboxLuuY);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Code.StaticVariable.messeseboxLuuY);
            }
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void ShowResult(DataTable _e, DataTable _tableView)
        {
            //convert _e to View
            bool duyet = false;
            DataTable view = new DataTable("View");
            foreach (DataColumn col in _e.Columns)
            {
                if (col.ColumnName == "DUYET")
                {
                    duyet = true;
                    view.Columns.Add(col.ColumnName, typeof(String));
                }
                else
                    view.Columns.Add(col.ColumnName, col.DataType);
            }

            for (int i = 0; i < _e.Rows.Count; i++)
            {
                view.Rows.Add(_e.Rows[i].ItemArray);
            }

            //add duyet
            if (duyet)
            {
                DataTable tblduyet = new DataTable("Duyet");
                tblduyet = _cl._services.GetDatatable_BySQL("select * from allcode where cdtype = 'AP' and cdname = 'DUYET' and cduser='Y' ORDER BY lstodr");
                for (int i = 0; i < view.Rows.Count; i++)
                {
                    for (int j = 0; j < tblduyet.Rows.Count; j++)
                    {
                        if (view.Rows[i]["DUYET"].ToString() == tblduyet.Rows[j]["CDVAL"].ToString())
                        {
                            view.Rows[i]["DUYET"] = tblduyet.Rows[j]["CDCONTENT"];
                            break;
                        }
                    }
                }
            }

            // Thay tên dựa theo FieldCode, FieldName
            this.dgvResult.DataSource = view;

            foreach (DataGridViewColumn column in this.dgvResult.Columns)
            {
                // kiem tra, neu column datatype = decimal --> format kieu khac
                if (column.ValueType == typeof(System.Decimal))
                {
                    column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    column.DefaultCellStyle.Format = "#,##0.###";
                }
                foreach (DataRow row in _tableView.Rows)
                {
                    if (row["fldname"].ToString() == column.HeaderText)
                    {
                        column.HeaderText = row["caption"].ToString();
                    }
                }
            }
        }

        private void txt_cmt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
            {
                try
                {
                    //chuyển sang Form View để tìm kiếm Sổ trái chủ
                    Forms.FrmView _FrmView = new Forms.FrmView("BSC_TBL_KHACHHANG", "Thông tin khách hàng", true);
                    _FrmView.ShowDialog();
                    //lấy về dữ liệu DataTable formView Khach hang
                    DataTable dt = Code.StaticVariable._tbl;
                    if (dt.Columns.Count >= 1 && dt.Rows.Count >= 1)
                    {
                        txt_cmt.Text = dt.Rows[0]["cmt"].ToString();
                    }
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
}
